package com.processor;

import com.annotation.CreateFile;
import com.google.auto.service.AutoService;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
import java.io.Writer;
import java.util.Set;

@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({"com.annotation.CreateFile"})
@AutoService(Processor.class)
public class CreateFileProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        Set<? extends Element> set = roundEnv.getElementsAnnotatedWith(CreateFile.class);
        for(Element element : set){
            CreateFile createFile = element.getAnnotation(CreateFile.class);
            if(element.getKind() == ElementKind.CLASS){
                String newFileName = createFile.fileName();
                StringBuilder newFileContent = new StringBuilder();
                newFileContent.append("package newFilePackage;\n");
                newFileContent.append("public class ");
                newFileContent.append(newFileName);
                newFileContent.append(" {\n");
                newFileContent.append(" private String name;\n");
                newFileContent.append(" }");

                Writer writer = null;

                try{
                    JavaFileObject file = filer.createSourceFile("com.javafile." + newFileName);
                    writer = file.openWriter();
                    writer.write(newFileContent.toString());
                    writer.flush();
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    closeWrite(writer);
                }
            }
        }
        return false;
    }

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        filer = processingEnv.getFiler();
    }
    private Filer filer;

    private void closeWrite(Writer writer){
        if (writer == null){
            return;
        }
        try{
            writer.close();
        }catch(Exception e){

        }
    }
}
